<template>
  <scroll-view class="booking-container" scroll-y refresher-enabled>
    <view class="booking-page">
    <!-- 座位信息卡片 -->
    <view class="seat-info-card card">
      <view class="card-header">
        <text class="card-title">座位信息</text>
        <view class="seat-status available">
          <text class="status-text">可预约</text>
        </view>
      </view>
      
      <view class="seat-details">
        <view class="seat-main">
          <text class="seat-number">{{ selectedSeat?.number }}</text>
          <text class="seat-area">{{ selectedSeat?.area }}</text>
        </view>
        <view class="seat-price">
          <text class="price-label">价格</text>
          <text class="price-value">¥{{ selectedSeat?.price }}/小时</text>
        </view>
      </view>
      
      <view class="equipment-info">
        <text class="equipment-title">设备配置</text>
        <view class="equipment-list">
          <view class="equipment-item">{{ selectedSeat?.equipment?.cpu }}</view>
          <view class="equipment-item">{{ selectedSeat?.equipment?.gpu }}</view>
          <view class="equipment-item">{{ selectedSeat?.equipment?.memory }}</view>
          <view class="equipment-item">{{ selectedSeat?.equipment?.monitor }}</view>
        </view>
      </view>
    </view>
    
    <!-- 时间选择卡片 -->
    <view class="time-selection-card card">
      <view class="card-header">
        <text class="card-title">时间选择</text>
      </view>
      
      <view class="time-item">
        <text class="time-label">开始时间</text>
        <picker 
          mode="datetime" 
          :value="startTime" 
          @change="onStartTimeChange"
          :start="minDateTime"
          :end="maxDateTime"
        >
          <view class="time-picker">
            <text class="time-text">{{ formatTime(startTime, 'MM-DD HH:mm') }}</text>
            <text class="picker-arrow">></text>
          </view>
        </picker>
      </view>
      
      <view class="time-item">
        <text class="time-label">使用时长</text>
        <picker 
          mode="selector" 
          :range="durationOptions" 
          :value="durationIndex"
          @change="onDurationChange"
        >
          <view class="time-picker">
            <text class="time-text">{{ durationOptions[durationIndex] }}</text>
            <text class="picker-arrow">></text>
          </view>
        </picker>
      </view>
      
      <view class="time-item">
        <text class="time-label">结束时间</text>
        <text class="end-time">{{ formatTime(endTime, 'MM-DD HH:mm') }}</text>
      </view>
    </view>
    
    <!-- 费用明细卡片 -->
    <view class="cost-detail-card card">
      <view class="card-header">
        <text class="card-title">费用明细</text>
      </view>
      
      <view class="cost-item">
        <text class="cost-label">基础费用</text>
        <text class="cost-value">¥{{ baseAmount.toFixed(2) }}</text>
      </view>
      
      <view v-if="memberDiscount > 0" class="cost-item discount">
        <text class="cost-label">会员折扣</text>
        <text class="cost-value">-¥{{ memberDiscount.toFixed(2) }}</text>
      </view>
      
      <view v-if="couponDiscount > 0" class="cost-item discount">
        <text class="cost-label">优惠券</text>
        <text class="cost-value">-¥{{ couponDiscount.toFixed(2) }}</text>
      </view>
      
      <view class="cost-divider"></view>
      
      <view class="cost-item total">
        <text class="cost-label">实付金额</text>
        <text class="cost-value">¥{{ totalAmount.toFixed(2) }}</text>
      </view>
    </view>
    
    <!-- 优惠券选择 -->
    <view class="coupon-card" @click="showCouponSelector">
      <view class="coupon-info">
        <text class="coupon-label">优惠券</text>
        <text class="coupon-text">{{ selectedCoupon ? selectedCoupon.name : '选择优惠券' }}</text>
      </view>
      <text class="coupon-arrow">></text>
    </view>
    
    <!-- 支付方式卡片 -->
    <view class="payment-method-card card">
      <view class="card-header">
        <text class="card-title">支付方式</text>
      </view>
      
      <view class="payment-item" v-for="method in paymentMethods" :key="method.id" @click="selectPaymentMethod(method)">
        <radio 
          :checked="selectedPaymentMethod?.id === method.id" 
          color="#007AFF"
        />
        <view class="payment-info">
          <text class="payment-icon">{{ method.icon }}</text>
          <view>
            <text class="payment-name">{{ method.name }}</text>
            <text v-if="method.balance !== undefined" class="payment-balance">余额: ¥{{ method.balance.toFixed(2) }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 底部操作栏 -->
    <view class="booking-actions safe-area-inset-bottom">
      <button 
        class="booking-btn" 
        :disabled="!canBook" 
        :class="{ disabled: !canBook, loading: booking }"
        @click="confirmBooking"
      >
        <view v-if="booking" class="loading-icon"></view>
        <text class="btn-text">{{ booking ? '预约中...' : `确认预约 ¥${totalAmount.toFixed(2)}` }}</text>
      </button>
    </view>
    
    <!-- 优惠券选择弹窗 -->
    <uni-popup
      ref="couponPopup"
      type="bottom"
      background-color="#fff"
      :z-index="999"
      @maskClick="closeCouponSelector"
    >
      <view class="coupon-selector">
        <view class="popup-header">
          <text class="popup-title">选择优惠券</text>
          <view class="popup-close" @click="closeCouponSelector" @tap="closeCouponSelector">
            <text class="close-icon">×</text>
          </view>
        </view>
        
        <scroll-view class="coupon-list" scroll-y>
          <view class="coupon-item" @click="selectCoupon(null)" :class="{ selected: !selectedCoupon }">
            <view class="coupon-content">
              <text class="coupon-name">不使用优惠券</text>
            </view>
          </view>
          
          <view 
            v-for="coupon in availableCoupons" 
            :key="coupon.id"
            class="coupon-item" 
            :class="{ selected: selectedCoupon?.id === coupon.id }"
            @click="selectCoupon(coupon)"
          >
            <view class="coupon-content">
              <text class="coupon-name">{{ coupon.name }}</text>
              <text class="coupon-desc">{{ coupon.description }}</text>
              <text class="coupon-expire">有效期至 {{ formatTime(coupon.expireTime, 'YYYY-MM-DD') }}</text>
            </view>
            <view class="coupon-amount">
              <text class="amount-text">¥{{ coupon.amount }}</text>
            </view>
          </view>
        </scroll-view>
      </view>
    </uni-popup>
    </view>
  </scroll-view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useSeatStore } from '@/stores/seat'
import { useUserStore } from '@/stores/user'
import { useOrderStore } from '@/stores/order'
import { formatTime, showError, showSuccess, showLoading, hideLoading } from '@/utils/common'

const seatStore = useSeatStore()
const userStore = useUserStore()
const orderStore = useOrderStore()

// 响应式数据
const startTime = ref(new Date())
const durationIndex = ref(1) // 默认2小时
const selectedCoupon = ref(null)
const selectedPaymentMethod = ref(null)
const booking = ref(false)
const couponPopup = ref(null)

// 时长选项
const durationOptions = ['1小时', '2小时', '3小时', '4小时', '5小时', '6小时', '8小时', '12小时']

// 支付方式
const paymentMethods = ref([
  { id: 'wechat', name: '微信支付', icon: '💬' },
  { id: 'alipay', name: '支付宝', icon: '🅰️' },
  { id: 'balance', name: '余额支付', icon: '💰', balance: userStore.balance }
])

// 模拟优惠券数据
const availableCoupons = ref([
  {
    id: 1,
    name: '新用户专享券',
    description: '满20减5',
    amount: 5,
    minAmount: 20,
    expireTime: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
  },
  {
    id: 2,
    name: '会员专属券',
    description: '满50减10',
    amount: 10,
    minAmount: 50,
    expireTime: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)
  }
])

// 计算属性
const selectedSeat = computed(() => seatStore.selectedSeatInfo)

const duration = computed(() => parseInt(durationOptions[durationIndex.value]))

const endTime = computed(() => {
  const end = new Date(startTime.value)
  end.setHours(end.getHours() + duration.value)
  return end
})

const baseAmount = computed(() => {
  if (!selectedSeat.value) return 0
  return selectedSeat.value.price * duration.value
})

const memberDiscount = computed(() => {
  if (!userStore.isLoggedIn) return 0
  // 会员折扣：银卡95折，金卡9折，VIP85折，钻石8折
  const discountRates = [0, 0.05, 0.1, 0.15, 0.2]
  const rate = discountRates[userStore.memberLevel] || 0
  return baseAmount.value * rate
})

const couponDiscount = computed(() => {
  if (!selectedCoupon.value) return 0
  if (baseAmount.value < selectedCoupon.value.minAmount) return 0
  return selectedCoupon.value.amount
})

const totalAmount = computed(() => {
  return Math.max(0, baseAmount.value - memberDiscount.value - couponDiscount.value)
})

const minDateTime = computed(() => {
  const now = new Date()
  return now.toISOString().slice(0, 16)
})

const maxDateTime = computed(() => {
  const max = new Date()
  max.setDate(max.getDate() + 7) // 最多提前7天预约
  return max.toISOString().slice(0, 16)
})

const canBook = computed(() => {
  return selectedSeat.value && 
         selectedPaymentMethod.value && 
         startTime.value && 
         duration.value > 0 &&
         !booking.value
})

// 方法
const onStartTimeChange = (e) => {
  startTime.value = new Date(e.detail.value)
}

const onDurationChange = (e) => {
  durationIndex.value = e.detail.value
}

const selectPaymentMethod = (method) => {
  selectedPaymentMethod.value = method
}

const showCouponSelector = () => {
  couponPopup.value.open()
}

const closeCouponSelector = () => {
  console.log('关闭优惠券选择弹窗')
  if (couponPopup.value) {
    couponPopup.value.close()
  }
}

const selectCoupon = (coupon) => {
  selectedCoupon.value = coupon
  closeCouponSelector()
}

const confirmBooking = async () => {
  if (!canBook.value) return
  
  // 检查余额支付
  if (selectedPaymentMethod.value.id === 'balance' && userStore.balance < totalAmount.value) {
    showError('余额不足，请选择其他支付方式')
    return
  }
  
  booking.value = true
  showLoading('预约中...')
  
  try {
    const orderData = {
      seatId: selectedSeat.value.id,
      seatNumber: selectedSeat.value.number,
      startTime: startTime.value,
      endTime: endTime.value,
      duration: duration.value,
      hourlyRate: selectedSeat.value.price,
      baseAmount: baseAmount.value,
      discountAmount: memberDiscount.value + couponDiscount.value,
      totalAmount: totalAmount.value,
      paymentMethod: selectedPaymentMethod.value.id,
      couponId: selectedCoupon.value?.id
    }
    
    const result = await orderStore.createOrder(orderData)
    
    if (result.success) {
      // 扣除余额
      if (selectedPaymentMethod.value.id === 'balance') {
        userStore.consumeBalance(totalAmount.value)
      }
      
      // 奖励积分
      const points = Math.floor(totalAmount.value)
      userStore.addPoints(points, '预约奖励')
      
      // 清除座位选择
      seatStore.clearSelection()
      
      showSuccess('预约成功！')
      
      // 跳转到订单详情
      setTimeout(() => {
        uni.redirectTo({
          url: `/pages/order/detail?id=${result.data.id}`
        })
      }, 1500)
    } else {
      showError(result.message || '预约失败')
    }
  } catch (error) {
    showError('预约失败，请重试')
  } finally {
    booking.value = false
    hideLoading()
  }
}

// 生命周期
onMounted(() => {
  // 检查是否有选择的座位
  if (!selectedSeat.value) {
    showError('请先选择座位')
    uni.navigateBack()
    return
  }
  
  // 设置默认开始时间为当前时间的下一个整点
  const now = new Date()
  now.setMinutes(0, 0, 0)
  now.setHours(now.getHours() + 1)
  startTime.value = now
  
  // 设置默认支付方式
  selectedPaymentMethod.value = paymentMethods.value[0]
})
</script>

<style lang="scss" scoped>
.booking-container {
  height: 100vh;
  background: var(--color-background);
}

.booking-page {
  min-height: 100vh;
  background: var(--color-background);
  padding: 16px;
  padding-bottom: 100px;
  overflow-x: hidden;
}

// 卡片基础样式
.card {
  background: white;
  border-radius: var(--radius-xl);
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: var(--shadow-sm);
  width: 100%;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--color-text-primary);
}

// 座位信息卡片
.seat-info-card {
  .seat-status {
    padding: 4px 12px;
    border-radius: var(--radius-md);
    font-size: 12px;
    font-weight: 500;

    &.available {
      background: rgba(52, 199, 89, 0.1);
      color: var(--color-success);
    }
  }

  .seat-details {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 16px;
    background: var(--color-background);
    border-radius: var(--radius-lg);
  }

  .seat-main {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .seat-number {
    font-size: 28px;
    font-weight: bold;
    color: var(--color-text-primary);
  }

  .seat-area {
    font-size: 14px;
    color: var(--color-text-secondary);
    padding: 2px 8px;
    background: white;
    border-radius: var(--radius-sm);
    align-self: flex-start;
  }

  .seat-price {
    text-align: right;
  }

  .price-label {
    font-size: 12px;
    color: var(--color-text-secondary);
    display: block;
    margin-bottom: 4px;
  }

  .price-value {
    font-size: 20px;
    font-weight: bold;
    color: var(--color-primary);
  }
}

.equipment-info {
  .equipment-title {
    font-size: 14px;
    font-weight: 600;
    color: var(--color-text-primary);
    margin-bottom: 12px;
    display: block;
  }

  .equipment-list {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }

  .equipment-item {
    background: var(--color-background);
    padding: 8px 12px;
    border-radius: var(--radius-md);
    font-size: 12px;
    color: var(--color-text-secondary);
    text-align: center;
  }
}

// 时间选择卡片
.time-selection-card {
  .time-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 0;
    border-bottom: 1px solid var(--color-border);

    &:last-child {
      border-bottom: none;
    }
  }

  .time-label {
    font-size: 16px;
    color: var(--color-text-primary);
    font-weight: 500;
  }

  .time-picker {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    background: var(--color-background);
    border-radius: var(--radius-md);
    min-width: 120px;
    justify-content: space-between;
  }

  .time-text {
    font-size: 14px;
    color: var(--color-text-primary);
  }

  .picker-arrow {
    font-size: 12px;
    color: var(--color-text-tertiary);
  }

  .end-time {
    font-size: 14px;
    color: var(--color-primary);
    font-weight: 500;
  }
}

// 费用明细卡片
.cost-detail-card {
  .cost-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;

    &.discount {
      .cost-value {
        color: var(--color-success);
      }
    }

    &.total {
      padding-top: 16px;

      .cost-label {
        font-size: 18px;
        font-weight: 600;
      }

      .cost-value {
        font-size: 20px;
        font-weight: bold;
        color: var(--color-error);
      }
    }
  }

  .cost-label {
    font-size: 14px;
    color: var(--color-text-secondary);
  }

  .cost-value {
    font-size: 16px;
    color: var(--color-text-primary);
    font-weight: 500;
  }

  .cost-divider {
    height: 1px;
    background: var(--color-border);
    margin: 12px 0;
  }
}

// 优惠券卡片
.coupon-card {
  background: white;
  border-radius: var(--radius-xl);
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: var(--shadow-sm);
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: transform var(--transition-fast);
  width: 100%;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
  min-height: 60px;

  &:active {
    transform: scale(0.98);
  }
}

.coupon-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.coupon-label {
  font-size: 16px;
  font-weight: 600;
  color: var(--color-text-primary);
}

.coupon-text {
  font-size: 14px;
  color: var(--color-primary);
}

.coupon-arrow {
  font-size: 16px;
  color: var(--color-text-tertiary);
}

// 支付方式卡片
.payment-method-card {
  .payment-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 16px 0;
    border-bottom: 1px solid var(--color-border);
    transition: all var(--transition-normal);

    &:last-child {
      border-bottom: none;
    }

    &:active {
      background: var(--color-background);
      margin: 0 -20px;
      padding: 16px 20px;
      border-radius: var(--radius-md);
    }
  }

  .payment-info {
    display: flex;
    align-items: center;
    gap: 12px;
    flex: 1;
  }

  .payment-icon {
    font-size: 24px;
  }

  .payment-name {
    font-size: 16px;
    color: var(--color-text-primary);
    font-weight: 500;
    display: block;
    margin-bottom: 2px;
  }

  .payment-balance {
    font-size: 12px;
    color: var(--color-text-secondary);
  }
}

// 底部操作栏
.booking-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 16px;
  border-top: 1px solid var(--color-border);
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.08);
  z-index: 1000;
}

.booking-btn {
  width: 100%;
  height: 56px;
  background: linear-gradient(135deg, var(--color-primary), var(--color-primary-light));
  color: white;
  border: none;
  border-radius: var(--radius-xl);
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  box-shadow: 0 4px 16px rgba(0, 122, 255, 0.3);
  transition: all var(--transition-normal);

  &:not(.disabled):not(.loading):active {
    transform: scale(0.98);
  }

  &.disabled {
    background: var(--color-text-tertiary);
    box-shadow: none;
  }

  &.loading {
    background: var(--color-text-tertiary);
  }
}

.loading-icon {
  width: 20px;
  height: 20px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top-color: white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.btn-text {
  color: white;
}

// 优惠券选择弹窗
.coupon-selector {
  background: white;
  border-radius: var(--radius-xl) var(--radius-xl) 0 0;
  max-height: calc(100vh - 120px);
  overflow: hidden;
  position: relative;
  z-index: 998;
  padding-bottom: 100px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid var(--color-border);
  position: sticky;
  top: 0;
  z-index: 1001;
  background: white;
}

.popup-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--color-text-primary);
}

.popup-close {
  width: 36px;
  height: 36px;
  border-radius: 18px;
  background: var(--color-background);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all var(--transition-normal);
  position: relative;
  z-index: 1002;
  cursor: pointer;

  &:active {
    transform: scale(0.9);
    background: var(--color-border);
  }

  &:hover {
    background: var(--color-border);
  }
}

.close-icon {
  font-size: 20px;
  color: var(--color-text-secondary);
}

.coupon-list {
  max-height: calc(100vh - 200px);
  padding: 0 20px 120px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.coupon-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  margin-bottom: 12px;
  background: var(--color-background);
  border-radius: var(--radius-lg);
  border: 2px solid transparent;
  transition: transform var(--transition-fast), border-color var(--transition-fast);
  width: 100%;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
  min-height: 80px;

  &.selected {
    border-color: var(--color-primary);
    background: rgba(0, 122, 255, 0.05);
  }

  &:active {
    transform: scale(0.98);
  }
}

.coupon-content {
  flex: 1;
  min-width: 0;
  overflow: hidden;
}

.coupon-name {
  font-size: 16px;
  font-weight: 600;
  color: var(--color-text-primary);
  display: block;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.coupon-desc {
  font-size: 14px;
  color: var(--color-text-secondary);
  display: block;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.coupon-expire {
  font-size: 12px;
  color: var(--color-text-tertiary);
}

.coupon-amount {
  text-align: right;
}

.amount-text {
  font-size: 20px;
  font-weight: bold;
  color: var(--color-primary);
}

// 响应式适配
@media (max-width: 375px) {
  .booking-page {
    padding: 12px;
    padding-bottom: 100px;
  }

  .card {
    padding: 16px;
  }

  .seat-number {
    font-size: 24px;
  }

  .price-value {
    font-size: 18px;
  }

  .equipment-list {
    grid-template-columns: 1fr;
  }
}
</style>
